package com.netmarch.jt809.controller;


import com.netmarch.jt809.server.BusiHandler;
import com.netmarch.jt809.server.Decoder;
import com.netmarch.jt809.server.Encoder;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.logging.LoggingHandler;
import org.jboss.netty.logging.InternalLogLevel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;


/**
 * @Author:Smile1
 * @Description:
 * @Date:11:25 AM2019/9/20
 */

@RestController
@RequestMapping("/socket")
public class controller {
    @Value("${socket.port}")
    private Integer socketport;

    @GetMapping("/start")
    public Object index() {
        ChannelFactory factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),
                Executors.newCachedThreadPool());

        ServerBootstrap bootstrap = new ServerBootstrap(factory);

        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            public ChannelPipeline getPipeline() {
                ChannelPipeline pipeline = Channels.pipeline();
                pipeline.addLast("loging", new LoggingHandler(InternalLogLevel.INFO));
                pipeline.addLast("decoder", new Decoder());
                pipeline.addLast("encoder", new Encoder());
                pipeline.addLast("busiHandler", new BusiHandler());

                return pipeline;
            }
        });

        bootstrap.setOption("child.tcpNoDelay", true);
        bootstrap.setOption("child.keepAlive", true);

        try {
            bootstrap.bind(new InetSocketAddress(socketport));
        } catch (Exception e) {
            e.printStackTrace();
            return "PORT IS ON";
        }

        System.out.println("JTServer startup ....");
        return "JTServer startup ....";
    }
}

